import requests
import json
import re
import os
import sys
import random
import time
cwd = os.getcwd()
sys.path.append(cwd)
print(cwd)

class ImageBaidu(object):
    url = 'https://image.baidu.com/search/index'
    # https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E9%BB%91%E8%89%B2%E8%BD%A6%E7%89%8C
    # 匹配图片url的正则表达式，如：https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2529022274,4196582660&fm=26&gp=0.jpg
    pattern_img_url = '"thumbURL":"(.*?)",'
    # 匹配图片后缀的正则表达式，如：jpg，png
    pattern_img_type = '"type":"(.*?)",'
    save_dir = './baidu_image' # 文件保存的路径
    count = 0

    # 初始化
    def __init__(self, word):
        self.word = word
        self.dir_path = os.path.join(self.save_dir, word)
        self.params = {
            'tn': 'resultjson_com',
            'ipn': 'rj',
            'ct': '201326592',
            'fp': 'result',
            'queryWord': word, # 需要搜索的关键字
            'word': word, # 需要搜索的关键字
            'width': '', # 宽度筛选
            'height': '', # 高度筛选
            'pn': '30', # 第0-30张
            'rn': '30', # 一次加载30个
        }
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
        }
        self.response = None
        # 创建保存图片的文件夹
        self.folder_exist(self.dir_path)

    # 请求包含图片url的网页
    def request(self):
        response = requests.get(url=self.url, headers=self.headers, params=self.params)
        response.encoding = 'utf8'
        if response.status_code == 200:
            self.response = response.text
        else:
            self.response = None

    # 正则匹配图片和图片后缀
    def match(self):
        list_img_url = re.findall(self.pattern_img_url, self.response)
        list_img_type = re.findall(self.pattern_img_type, self.response)
        return (list_img_url, list_img_type)

    # 下载一张图片
    def download(self, img_url, img_type):
        self.count += random.randint(2000,10000)
        time.sleep(1)
        print('正在下载第%d张图片...'%self.count)
        response = requests.get(img_url, headers=self.headers)
        img_name = str(self.count) + '.' + img_type
        img_path = os.path.join(self.dir_path, img_name)
        with open(img_path, 'wb') as f:
            f.write(response.content)

    # 下载所有图片
    def download_all(self):
        # 图片最多加载1000页
        for i in range(1, 1001):
            self.params['pn'] = str(30*i)
            self.request()
            if self.response != None:
                list_img_url, list_img_type = self.match()
                for index in range(len(list_img_url)):
                    self.download(list_img_url[index], list_img_type[index])
            else:
                print('下载图片完成')
                break
        self.count = 0

    def folder_exist(self, dir_path):
        '''
        1. 作用:判断文件夹路径是否存在,不存在则创建
        2. 参数:dir_path:文件夹路径
        3. 返回值:None
        '''
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

if __name__ == '__main__':
    image = ImageBaidu('黑色牌照')
    image.download_all()